#!/usr/local/bin/lua
-- 加载初始化文件，确保模块路径正确
package.path = package.path .. ";/usr/local/share/lua/5.3/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.3/?.so"
require('init')

-- 加载 luasql.mysql 模块
local luasql = require('luasql.mysql')

-- 创建环境对象
local env = luasql.mysql()

-- 连接数据库
local conn, err = env:connect("user", "root", "hdp123456", "127.0.0.1", 3306)
if not conn then
    print("Error connecting to database: " .. err)
    return
end

-- 设置数据库的编码格式                                                                           
conn:execute("SET NAMES UTF8")

-- 执行数据库操作
local cur = conn:execute("select * from users")

-- 获取一行数据
local row = cur:fetch({}, "a")


-- 遍历结果集并写入文件
while row do
    print("id:", row.id)
    print("ip:", row.ip)
    print("count:", row.count)

    local var = string.format("%d %s %d\n", row.id, row.ip,row.count)
    print(var)
    row = cur:fetch(row, "a")
end

conn:close() -- 关闭数据库连接
env:close() -- 关闭数据库环境